package com.bjpowerndoe.ylb.web.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.bjpowerndoe.ylb.common.RedisKey;
import com.bjpowerndoe.ylb.web.enums.CodeEnum;
import com.bjpowerndoe.ylb.web.model.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import springfox.documentation.swagger.readers.operation.OperationNicknameIntoUniqueIdReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 *  验证token拦截器
 */
public class TokenInterceptor  implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public TokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*  1.验证token， 从header中获取token， 和redis中的存储token比较
            2.如果一样，执行请求，给Controller
            3.如果不一样， 返回错误信息， 在preHandle方法中返回错误信息（自定义）
         */
        // 过滤掉OPTIONS
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }

        boolean checkToken  = false;
        //获取post请求中的token  Bearer da2ea35d254e40249b57943c93dfa803
        String authorization = request.getHeader("Authorization");
        if(StrUtil.isNotBlank(authorization) && authorization.startsWith("Bearer")){
            String token = authorization.substring(7);
            if( StrUtil.isNotBlank(token)){
                //和redis比较
                String key = RedisKey.TOKEN_LOGIN + token.toUpperCase();
                if( stringRedisTemplate.hasKey(key)){
                    String saveUid = (String)stringRedisTemplate.opsForHash().get(key,"uid");
                    String headerUid = request.getHeader("uid");
                    if( saveUid != null && headerUid != null){
                        checkToken = saveUid.equals(headerUid);
                    }
                }
            }
        }
        if( !checkToken){
            //token验证失败，自定义返回结果
            CommonResult commonResult = CommonResult.fail(CodeEnum.TOKEN_INVALID_ERR);
            String json = JSONUtil.toJsonStr(commonResult);
            //应答输出
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(json);
            out.flush();
            out.close();
        }
        return checkToken;
    }
}
